Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Google Medium
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Google Hard
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Nth Magical Number

Problem Statement

Given the three integers n, a, and b, return the nth magical number modulo + 7 as it can be very large.

A positive integer is called magical if it is divisible by either a or b.

Examples

  • Example 1:

    • Input: n = 3, a = 2, b = 3
    • Expected Output: 4
    • Justification: The first three magical numbers divisible by 2 or 3 are 2, 3, and 4. The third magical number is 4.
  • Example 2:

    • Input: n = 5, a = 3, b = 4
    • Expected Output: 9
    • Justification: The sequence of magical numbers that are divisible by 3 or 4 begins as 3, 4, 6, 8, 9. The fifth one in this sequence is 9.
  • Example 3:

    • Input: n = 20, a = 3, b = 5
    • Expected Output: 42
    • Justification: The 20th magical number for a = 30, and b = 5 is 42.

Solution

To solve this problem, we leverage the concept of binary search along with some mathematical principles to efficiently find the nth "magical number." A magical number, in this context, is defined as any positive integer that is divisible by either of two given numbers, A or B. The key to solving this problem lies in understanding how these numbers distribute over a range and utilizing the least common multiple (LCM) of A and B to avoid redundancy. The solution involves a binary search strategy, focusing on narrowing down the range within which the nth magical number lies by counting the number of magical numbers up to a certain point and adjusting the search bounds accordingly. This method significantly reduces the number of checks needed compared to a linear search, especially for large values of N, A, and B.

The algorithm's effectiveness is rooted in its use of mathematical properties to simplify the problem. By calculating the LCM of A and B, we can accurately determine the intervals at which magical numbers occur and leverage this to estimate the position of the nth magical number within a bounded search space. Combining this with the efficiency of binary search, we can quickly converge on the exact value of the nth magical number. This approach minimizes computational overhead and ensures that the solution can handle large input values without performance degradation, making it an optimal strategy for solving the given problem.

Step-by-Step Algorithm

  1. Calculate the Least Common Multiple (LCM) of A and B using the Greatest Common Divisor (GCD) method. This is crucial for accurately identifying the distribution of magical numbers.
  2. Initialize the search bounds: Set the lower bound (lo) to 0 and the upper bound (hi) to N * min(A, B). This range guarantees that the nth magical number lies within.
  3. Perform binary search: Repeat the following steps until lo is less than hi:
    • Calculate the mid-point (mi) as lo + (hi - lo) / 2.
    • Count the total number of magical numbers less than or equal to mi by adding the numbers divisible by A, those divisible by B, and subtracting those divisible by both (to avoid double counting).
    • If the count is less than N, adjust lo to mi + 1 to search the upper half. Otherwise, adjust hi to mi to search the lower half.
  4. Return the result: Once the loop concludes, lo will be the nth magical number. Return lo % MOD to ensure the result is within the integer limit.

Algorithm Walkthrough

Let's consider the Input: n = 20, a = 3, b = 5

  1. Calculate LCM and Initialize:

    • The LCM of 3 and 5 is found using the gcd function: LCM(3, 5) = 15.
    • Set MOD = 1_000_000_007.
    • Initialize search bounds: lo = 0, hi = 60 (since n * min(a, b) = 20 * 3 = 60).
  2. Binary Search Iterations:

    • Iteration 1:
      • Mid = (0 + 60) / 2 = 30.
      • Count = 30 / 3 + 30 / 5 - 30 / 15 = 10 + 6 - 2 = 14. Since 14 < 20, lo becomes 31.
    • Iteration 2:
      • New bounds are lo = 31, hi = 60.
      • Mid = (31 + 60) / 2 = 45.5 (using integer division, Mid = 45).
      • Count = 45 / 3 + 45 / 5 - 45 / 15 = 15 + 9 - 3 = 21. Since 21 >= 20, hi becomes 45.
    • Iteration 3:
      • New bounds are lo = 31, hi = 45.
      • Mid = (31 + 45) / 2 = 38.
      • Count = 38 / 3 + 38 / 5 - 38 / 15 = 12 + 7 - 2 = 17. Since 17 < 20, lo becomes 39.
    • Iteration 4:
      • New bounds are lo = 39, hi = 45.
      • Mid = (39 + 45) / 2 = 42.
      • Count = 42 / 3 + 42 / 5 - 42 / 15 = 14 + 8 - 2 = 20. Since 20 == 20, and we're looking for the least value of lo that meets this condition, hi becomes 42.
    • Iteration 5:
      • New bounds are lo = 39, hi = 42.
      • Mid = (39 + 42) / 2 = 40.5 (using integer division, Mid = 40).
      • Count = 40 / 3 + 40 / 5 - 40 / 15 = 13 + 8 - 2 = 19. Since 19 < 20, lo becomes 41.
    • Iteration 6:
      • New bounds are lo = 41, hi = 42.
      • Mid = (41 + 42) / 2 = 41.5 (using integer division, Mid = 41).
      • Count = 41 / 3 + 41 / 5 - 41 / 15 = 13 + 8 - 2 = 19 (same as last time, since Mid didn't change effectively). Since 19 < 20, lo becomes 42.
    • Iteration 7:
      • Now lo = 42 and hi = 42, so the loop terminates.
  3. Final Result:

    • The loop has exited with lo = 42, which is the value we consider to be the 20th magical number given a = 3 and b = 5.
  4. Modulus Operation:

    • Apply the modulus operation: 42 % MOD = 42.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  • : The main operation in this code is the binary search algorithm. The search space is between 0 and . The binary search algorithm has a logarithmic time complexity relative to the size of the search space. Therefore, the time complexity is , as each iteration of the loop halves the search space until the solution is found.

Space Complexity

  • : The algorithm uses a constant amount of space regardless of the input size. Thus, the space complexity of the algorithm is , indicating that it uses a fixed amount of memory.
Nth Magical Number (hard)
Candy (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity